const express = require('express');
const router = express.Router();
const axios = require('axios');

// DeepSeek API配置 - 通过环境变量设置
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;
const DEEPSEEK_API_BASE = 'https://api.deepseek.com/v1';

// 聊天补全接口
router.post('/chat', async (req, res) => {
  try {
    const { messages, model = 'deepseek-chat', temperature = 0.7, max_tokens = 2048 } = req.body;

    // 参数验证
    if (!messages || !Array.isArray(messages)) {
      return res.status(400).json({
        error: '参数错误',
        message: 'messages字段是必需的且必须为数组'
      });
    }

    const response = await axios.post(
      `${DEEPSEEK_API_BASE}/chat/completions`,
      {
        model,
        messages,
        temperature,
        max_tokens
      },
      {
        headers: {
          'Authorization': `Bearer ${DEEPSEEK_API_KEY}`,
          'Content-Type': 'application/json'
        },
        timeout: 30000
      }
    );

    res.json(response.data);

  } catch (error) {
    console.error('DeepSeek API错误:', error.response?.data || error.message);

    if (error.response) {
      res.status(error.response.status).json({
        error: 'DeepSeek API错误',
        message: error.response.data.error?.message || 'API调用失败'
      });
    } else if (error.request) {
      res.status(503).json({
        error: '网络错误',
        message: '无法连接到DeepSeek服务'
      });
    } else {
      res.status(500).json({
        error: '服务器错误',
        message: error.message
      });
    }
  }
});

// 获取模型列表
router.get('/models', async (req, res) => {
  try {
    const response = await axios.get(
      `${DEEPSEEK_API_BASE}/models`,
      {
        headers: {
          'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
        }
      }
    );

    res.json(response.data);

  } catch (error) {
    console.error('获取模型列表错误:', error);
    res.status(500).json({
      error: '获取模型列表失败',
      message: error.response?.data?.error?.message || error.message
    });
  }
});

// 健康检查
router.get('/health', (req, res) => {
  res.json({ 
    status: 'ok', 
    service: 'deepseek-api',
    timestamp: new Date().toISOString()
  });
});

module.exports = router;